import _ from 'lodash';

export const generateSerializedNodes = (nodes) => {
  const parentKeys = [];
  const nodeTree = [];
  const loop = (list, children, key) => {
    if (list[key]) {
      const componentName = list[key]?.type?.resolvedName;
      const currentNode = {
        key,
        componentName,
        title: list[key].displayName || componentName,
        props: _.pickBy(
          list[key].props,
          (v, k) =>
            !_.includes(
              ['data-inspector-line', 'data-inspector-column', 'data-inspector-relative-path'],
              k,
            ),
        ),
      };
      const { linkedNodes, nodes: childNodes } = list[key];
      const childKeys = _.concat(_.values(linkedNodes), childNodes);
      if (childKeys.length) {
        parentKeys.push(key);
        currentNode.children = [];
        children.push(currentNode);
        _.forEach(childKeys, (nextKey) => {
          loop(list, currentNode.children, nextKey);
        });
      } else {
        children.push(currentNode);
      }
    }
  };
  loop(nodes, nodeTree, 'ROOT');
  return { nodeTree, parentKeys };
};
